package com.lanzchina.lanclass.service;

import com.lanzchina.lanclass.constant.Constant;
import com.lanzchina.lanclass.domain.Result;
import com.lanzchina.lanclass.domain.School;
import com.lanzchina.lanclass.domain.User;
import com.lanzchina.lanclass.repository.SchoolRepository;
import com.lanzchina.lanclass.repository.UserRepository;
import com.lanzchina.lanclass.utils.Md5Util;
import com.lanzchina.lanclass.utils.ResultUtil;
import jdk.nashorn.internal.ir.ReturnNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by qiangjindong
 * 2018-08-11 16:16
 */
@Service
public class LoginService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private SchoolRepository schoolRepository;

    @Autowired
    private UserService userService;

    @Autowired
    private OpenIdService openIdService;

    /**
     * 登录接口
     *
     * @param userAccount  用户账号
     * @param password     用户密码
     * @param schoolCode   学校码，防止多个学校有重复账号
     * @param code         获取当前openId，用于判断用户账号是否绑定了其他openId
     * @param validateCode 验证码
     * @return 用户
     */
    public Result login(String userAccount, String password, Integer schoolCode, String code, String validateCode) {
        // 第一步，验证校验码
        String myValidateCode = Md5Util.validateCode("userAccount", userAccount);
        if (!myValidateCode.equals(validateCode)) {
            return ResultUtil.error(0, "验证失败");
        }

        // 第二步，通过schoolCode和userAccount查找用户
        School school = schoolRepository.findBySchoolCode(schoolCode);
        if (school == null) {
            return ResultUtil.error(0, "schoolCode有误");
        }

        User user = userRepository.findBySchoolAndUserAccount(school, userAccount);
        if (user == null) {
            return ResultUtil.error(0, "该用户账号不存在");
        }

        // 第三步，验证密码
        if (!Md5Util.md5(user.getPassword()).equals(password)) {
            return ResultUtil.error(0, "密码错误");
        }

        // 第四步，验证该用户账号是否绑定了其他openId
        String openId = user.getOpenId();
        if (openId != null) {
            // 提示用户，用户账户已经绑定其他openId
        }

        // 第五步，进行账号绑定
        user.setOpenId(openId);
        userRepository.save(user);

        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("userInfo", userService.formatUserInfo(user));
        return ResultUtil.success(userInfo);
    }
}
